import Taro from '@tarojs/taro'
import React, { PureComponent } from 'react'
// 界面组件
import { View, Picker, Button } from '@tarojs/components'
import { AtInput, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui'
import CTopbar from '@/components/CTopBar/index'
import CList from '@/components/CList'
import './index.scss'
import GetTopBarInfo from '@/utils/GetTopBarInfo' //动态高度
import { edit_my_info, get_my_setting_info_api, upload_address_api } from './service'
import GetBaseUrl from '@/server/baseUrl'
import dataList from './address.json'
/**
 * 设置界面
 */
class SetUp extends PureComponent<any, any> {
  constructor(props) {
    super(props)
    this.state = {
      nickName: '',
      isOpened: false,
      my_info: {},
      province: '', //省
      city: '', //市
      area: '', //区
      cityAreaList: [], //市区数组
      pickerValue: [0, 0, 0], // 默认选中的省市区下标
    }
  }

  provinceList: Array<string> = [] //省
  cityList: Array<string> = [] //市
  areaList: Array<string> = [] //区
  index = 0 //多列选择器第1列选中的value值下标
  componentWillMount() {
    console.log(dataList)

    this.get_my_info()

    // 初始化市区
    // 省
    for (let i = 0; i < dataList.length; i++) {
      this.index = 0
      this.provinceList.push(dataList[i].province)
    }
    //市
    if (dataList[0].city.length != 0) {
      for (let i = 0; i < dataList[0].city.length; i++) {
        if (dataList[0].city[i].name != '县' && dataList[0].city[i].name != '市') {
          //过滤县与市
          this.cityList.push(dataList[0].city[i].name)
        }
      }
    } else {
      this.cityList = []
    }
    //区
    if (dataList[0].city.length != 0) {
      if (dataList[0].city[0].county) {
        //如果区存在
        for (let i = 0; i < dataList[0].city[0].county.length; i++) {
          this.areaList.push(dataList[0].city[0].county[i])
        }
      } else {
        this.areaList = []
      }
    }

    //修改省市区显示
    const newCityAreaList = [this.provinceList, this.cityList, this.areaList]
    this.setState({ cityAreaList: [...newCityAreaList] })
  }

  get_my_info() {
    get_my_setting_info_api().then(({ result, data }) => {
      this.setState({
        my_info: data,
      })
      // 重新存储storage
      Taro.setStorage({
        key: 'user_info',
        data,
      })
    })
  }
  // 打开模态框
  openModal() {
    this.setState({
      isOpened: true,
      nickName: this.state.my_info.nickName,
    })
  }
  // 关闭模态框
  onClose() {
    this.setState({
      isOpened: false,
    })
  }
  // 取消按钮
  onCancel() {
    this.setState({
      isOpened: false,
    })
  }
  // 确定按钮
  onConfirm() {
    const { nickName } = this.state
    if (!nickName) {
      Taro.showToast({
        title: '昵称不能为空',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    const params = {
      nickName: nickName,
      userName: nickName,
    }
    edit_my_info(params).then(({ result, data, message }) => {
      if (result < 0) {
        Taro.showToast({
          title: message,
          icon: 'none',
          duration: 2000,
        })
        return
      }

      // 刷新请求
      this.get_my_info()
      // 关闭弹窗
      this.setState({
        isOpened: false,
      })
    })
  }

  selectFile() {
    const that = this
    Taro.chooseImage({
      count: 1,
      success: (result) => {
        const imgUrl = result.tempFilePaths[0]
        console.log(imgUrl)

        const authorization = Taro.getStorageSync('authorization')

        Taro.showLoading({
          title: '上传中',
        })
        Taro.uploadFile({
          url: GetBaseUrl('/api/applets/user/uploadHeadPortraitUri'),
          filePath: imgUrl,
          name: 'file',
          header: {
            authorization: authorization,
            'Content-Type': 'multipart/form-data',
          },
          success(res) {
            // 刷新请求
            that.get_my_info()
            // 取消loading
            Taro.hideLoading()
          },
          fail(res) {
            // 取消loading
            Taro.hideLoading()
            Taro.showToast({
              title: '上传失败',
              icon: 'none',
              duration: 2000,
            })
          },
        })
      },
      fail: (err) => {
        console.log(err)
      },
    })
  }

  onChangeAddress(e) {
    console.log(e)
  }

  // 当省变化时对应的市变化，当市变化对应的区变化
  handleColChange = (e) => {
    const currentIndex = e.target.value // 正在滑动列的下标

    if (dataList[currentIndex].city.length != 0) {
      console.log(currentIndex)

      const selectColumn = e.detail.column // 选中的第几列

      if (selectColumn == 0) {
        //判断第1列value值省发生了变化
        this.index = currentIndex

        // 获取对应省的 所有市
        const cityList = dataList[currentIndex].city
        const cityListArr = cityList.map((item) => item.name)
        // 获取第一个市对应的所有区
        const haveCounty = cityList[0].county.length > 0
        const areaListArr = haveCounty ? cityList[0].county : []
        console.log(this.provinceList)

        const provinceListArr = this.provinceList
        console.log(provinceListArr, cityListArr, areaListArr)
        this.cityList = cityListArr
        this.setState({
          pickerValue: [currentIndex, 0, 0],
          cityAreaList: [provinceListArr, cityListArr, areaListArr],
        })
      }
      //判断第2列value值变化
      if (selectColumn == 1) {
        // 获取所有区
        const countyListArr = dataList[this.index].city[currentIndex].county
        const cityListArr = this.cityList
        this.areaList = countyListArr
        const provinceListArr = this.provinceList
        this.setState({
          pickerValue: [this.state.pickerValue[0], currentIndex, 0],
          cityAreaList: [provinceListArr, cityListArr, countyListArr],
        })
      } else {
      }
    }
  }
  onClickConfirmChange = (e) => {
    this.setState(
      {
        province: this.state.cityAreaList[0][e.detail.value[0]],
        city: this.state.cityAreaList[1][e.detail.value[1]],
        area: this.state.cityAreaList[2][e.detail.value[2]],
      },
      () => {
        console.log(this.state)
        this.upload_address(this.state.province + this.state.city + this.state.area)
      },
    )
  }

  upload_address(address) {
    upload_address_api(address).then(({ result, data }) => {
      console.log(data)
      this.get_my_info()
    })
  }
  handleNameChange(value) {
    this.setState({
      nickName: value,
    })
  }

  render() {
    const { my_info, isOpened } = this.state

    return (
      <View style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
        <CTopbar title='设置' showBack></CTopbar>
        <View className='content'>
          <View className='title'>基本信息</View>

          <View className='wrapper'>
            <View className='section' onClick={this.selectFile.bind(this)}>
              <CList title='头像' isarrow imgSrc={my_info.avatarUrl}></CList>
            </View>

            <View className='section_2' onClick={this.openModal.bind(this)}>
              <CList title='昵称' extraText={my_info.nickName}></CList>
            </View>

            <View className='section_2'>
              {/* 
              *  mode="multiSelector" // 多列选择
                onChange={this.onChange} // change事件
                onColumnChange={this.onColumnChange} // 某列改变的事件
                range={rangeData} //需要展示的数据
                value={rangeKey} // 选择的下标
              *
               */}
              <Picker
                mode='multiSelector'
                value={this.state.pickerValue}
                range={this.state.cityAreaList}
                onChange={this.onClickConfirmChange.bind(this)}
                onColumnChange={this.handleColChange.bind(this)}
              >
                <CList title='地址' isarrow extraText={my_info.address || ''}></CList>
              </Picker>
            </View>
          </View>

          {/* 模态框 */}
          <View className='modalWrapper'>
            <AtModal isOpened={isOpened} onClose={this.onClose.bind(this)}>
              <AtModalHeader>修改昵称</AtModalHeader>
              <AtModalContent>
                <AtInput
                  name='nickName'
                  title='昵称：'
                  type='text'
                  placeholder='昵称'
                  value={this.state.nickName}
                  onChange={this.handleNameChange.bind(this)}
                />
              </AtModalContent>
              <AtModalAction>
                <Button onClick={this.onCancel.bind(this)}>取消</Button> <Button onClick={this.onConfirm.bind(this)}>确定</Button>
              </AtModalAction>
            </AtModal>
          </View>
        </View>
      </View>
    )
  }
}

export default SetUp
